package com.anjiplus.template.gaea.business.modules.inf.event;

import com.anji.plus.gaea.inf.event.DynamicSqlEventSource;
import com.anji.plus.gaea.inf.event.DynamicSqlExecuteSuccessEvent;
import com.anjiplus.template.gaea.business.modules.inf.app.dao.GaeaInfAppRelationMapper;
import com.anjiplus.template.gaea.business.modules.inf.app.dao.entity.GaeaInfAppRelation;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * @ClassName DynamicSqlExecuteSuccessListener
 * @Description: SQL执行成功监听器
 * @Author dingkaiqiang
 * @Date 2021-03-26
 * @Version V1.0
 **/

@Slf4j
@Component
public class DynamicSqlExecuteSuccessListener implements ApplicationListener<DynamicSqlExecuteSuccessEvent> {

    @Autowired
    private GaeaInfAppRelationMapper infAppRelationMapper;

    @Override
    public void onApplicationEvent(DynamicSqlExecuteSuccessEvent dynamicSqlExecuteSuccessEvent) {
        try {
            DynamicSqlEventSource source = (DynamicSqlEventSource) dynamicSqlExecuteSuccessEvent.getSource();
            LambdaUpdateWrapper<GaeaInfAppRelation> wrapper = Wrappers.<GaeaInfAppRelation>lambdaUpdate()
                    .eq(GaeaInfAppRelation::getInfName, source.getInfName())
                    .eq(GaeaInfAppRelation::getAppId, source.getAppId())
                    .setSql("times = times - 1");
            int update = infAppRelationMapper.update(null, wrapper);
            log.info("SQL执行修改调用次数完成,{}", update);
        } catch (Exception e) {
            log.error("SQL执行修改调用次数失败，{}", e.getMessage());
        }
    }
}
